package com.taobao.diamond.server.controller;

import com.taobao.diamond.common.Constants;
import com.taobao.diamond.domain.ConfigInfo;
import com.taobao.diamond.domain.ConfigInfoEx;
import com.taobao.diamond.domain.Page;
import com.taobao.diamond.server.exception.ConfigServiceException;
import com.taobao.diamond.server.service.AdminService;
import com.taobao.diamond.server.service.ConfigService;
import com.taobao.diamond.server.service.OperatorEnum;
import com.taobao.diamond.server.service.OperatorRecordService;
import com.taobao.diamond.server.utils.DiamondUtils;
import com.taobao.diamond.server.utils.GlobalCounter;
import com.taobao.diamond.utils.JSONUtils;
import com.taobao.diamond.utils.TimeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/22 0022.---------test
 */


@Controller
@RequestMapping({"/admin.do"})
public class AdminController {
    private static final Log log = LogFactory.getLog(AdminController.class);
    @Autowired
    private AdminService adminService;
    @Autowired
    private ConfigService configService;
    @Resource
    private OperatorRecordService operatorRecordService;



    @RequestMapping(
            params = {"method=postConfig"},
            method = {RequestMethod.POST}
    )
    public String postConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        boolean checkSuccess = true;
        String errorMessage = "参数错误";
        if(StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
            checkSuccess = false;
            errorMessage = "无效的DataId";
        }

        if(StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
            checkSuccess = false;
            errorMessage = "无效的分组";
        }

        if(StringUtils.isBlank(content)) {
            checkSuccess = false;
            errorMessage = "无效的内容";
        }

        if(!checkSuccess) {
            modelMap.addAttribute("message", errorMessage);
            return "/admin/config/new";
        } else {
            dataId = dataId.trim();
            group = group.trim();
            String userName = (String)request.getSession().getAttribute("user");
            Timestamp time = TimeUtils.getCurrentTime();

            try {
                this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.ADD.toString(), dataId, group, content, content, time);
            } catch (Exception var12) {
                log.error("记录操作日志转json字符串异常");
            }

            this.configService.addConfigInfo(dataId, group, content);
            modelMap.addAttribute("message", "提交成功!");
            return this.listConfig(request, response, dataId, group, 1, 20, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=deleteConfig"},
            method = {RequestMethod.GET}
    )
    public String deleteConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") long id, ModelMap modelMap) {
        ConfigInfo configInfo = this.configService.getConfigInfoById(id);
        if(configInfo != null) {
            String userName = (String)request.getSession().getAttribute("user");
            Timestamp time = TimeUtils.getCurrentTime();

            try {
                this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.DELETE.toString(), configInfo.getDataId(), configInfo.getGroup(), configInfo.getContent(), configInfo.getContent(), time);
            } catch (Exception var10) {
                log.error("记录操作日志转json字符串异常");
            }
        }

        this.configService.removeConfigInfo(id);
        modelMap.addAttribute("message", "删除成功!");
        return "/admin/config/list";
    }

    @RequestMapping(
            params = {"method=upload"},
            method = {RequestMethod.POST}
    )
    public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        boolean checkSuccess = true;
        String errorMessage = "参数错误";
        if(StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
            checkSuccess = false;
            errorMessage = "无效的DataId";
        }

        if(StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
            checkSuccess = false;
            errorMessage = "无效的分组";
        }

        String content = this.getContentFromFile(contentFile);
        if(StringUtils.isBlank(content)) {
            checkSuccess = false;
            errorMessage = "无效的内容";
        }

        if(!checkSuccess) {
            modelMap.addAttribute("message", errorMessage);
            return "/admin/config/upload";
        } else {
            String userName = (String)request.getSession().getAttribute("user");
            Timestamp time = TimeUtils.getCurrentTime();

            try {
                this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.ADD.toString(), dataId, group, content, content, time);
            } catch (Exception var13) {
                log.error("记录操作日志转json字符串异常");
            }

            this.configService.addConfigInfo(dataId, group, content);
            modelMap.addAttribute("message", "提交成功!");
            return this.listConfig(request, response, dataId, group, 1, 20, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=reupload"},
            method = {RequestMethod.POST}
    )
    public String reupload(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        boolean checkSuccess = true;
        String errorMessage = "参数错误";
        String content = this.getContentFromFile(contentFile);
        ConfigInfo configInfo = new ConfigInfo(dataId, group, content);
        if(StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
            checkSuccess = false;
            errorMessage = "无效的DataId";
        }

        if(StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
            checkSuccess = false;
            errorMessage = "无效的分组";
        }

        if(StringUtils.isBlank(content)) {
            checkSuccess = false;
            errorMessage = "无效的内容";
        }

        if(!checkSuccess) {
            modelMap.addAttribute("message", errorMessage);
            modelMap.addAttribute("configInfo", configInfo);
            return "/admin/config/edit";
        } else {
            String userName = (String)request.getSession().getAttribute("user");
            Timestamp time = TimeUtils.getCurrentTime();

            try {
                this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.ADD.toString(), dataId, group, content, content, time);
            } catch (Exception var14) {
                log.error("记录操作日志转json字符串异常");
            }

            this.configService.updateConfigInfo(dataId, group, content);
            modelMap.addAttribute("message", "更新成功!");
            return this.listConfig(request, response, dataId, group, 1, 20, modelMap);
        }
    }

    private String getContentFromFile(MultipartFile contentFile) {
        try {
            String charset = "GBK";
            String content = new String(contentFile.getBytes(), charset);
            return content;
        } catch (Exception var4) {
            throw new ConfigServiceException(var4);
        }
    }

    @RequestMapping(
            params = {"method=updateConfig"},
            method = {RequestMethod.POST}
    )
    public String updateConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("content") String content, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        ConfigInfo configInfo = new ConfigInfo(dataId, group, content);
        boolean checkSuccess = true;
        String errorMessage = "参数错误";
        if(StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
            checkSuccess = false;
            errorMessage = "无效的DataId";
        }

        if(StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
            checkSuccess = false;
            errorMessage = "无效的分组";
        }

        if(StringUtils.isBlank(content)) {
            checkSuccess = false;
            errorMessage = "无效的内容";
        }

        if(!checkSuccess) {
            modelMap.addAttribute("message", errorMessage);
            modelMap.addAttribute("configInfo", configInfo);
            return "/admin/config/edit";
        } else {
            String userName = (String)request.getSession().getAttribute("user");
            Timestamp time = TimeUtils.getCurrentTime();

            try {
                this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.UPDATE.toString(), dataId, group, content, content, time);
            } catch (Exception var13) {
                log.error("记录操作日志转json字符串异常", var13);
            }

            this.configService.updateConfigInfo(dataId, group, content);
            modelMap.addAttribute("message", "提交成功!");
            return this.listConfig(request, response, dataId, group, 1, 20, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=listConfig"},
            method = {RequestMethod.GET}
    )
    public String listConfig(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) {
        Page<ConfigInfo> page = this.configService.findConfigInfo(pageNo, pageSize, group, dataId);
        String accept = request.getHeader("Accept");
        if(accept != null && accept.indexOf("application/json") >= 0) {
            try {
                String json = JSONUtils.serializeObject(page);
                modelMap.addAttribute("pageJson", json);
            } catch (Exception var11) {
                log.error("序列化page对象出错", var11);
            }

            return "/admin/config/list_json";
        } else {
            modelMap.addAttribute("dataId", dataId);
            modelMap.addAttribute("group", group);
            modelMap.addAttribute("page", page);
            return "/admin/config/list";
        }
    }

    @RequestMapping(
            params = {"method=listConfigLike"},
            method = {RequestMethod.GET}
    )
    public String listConfigLike(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, ModelMap modelMap) {
        if(StringUtils.isBlank(dataId) && StringUtils.isBlank(group)) {
            modelMap.addAttribute("message", "模糊查询请至少设置一个查询参数");
            return "/admin/config/list";
        } else {
            Page<ConfigInfo> page = this.configService.findConfigInfoLike(pageNo, pageSize, group, dataId);
            String accept = request.getHeader("Accept");
            if(accept != null && accept.indexOf("application/json") >= 0) {
                try {
                    String json = JSONUtils.serializeObject(page);
                    modelMap.addAttribute("pageJson", json);
                } catch (Exception var11) {
                    log.error("序列化page对象出错", var11);
                }

                return "/admin/config/list_json";
            } else {
                modelMap.addAttribute("page", page);
                modelMap.addAttribute("dataId", dataId);
                modelMap.addAttribute("group", group);
                modelMap.addAttribute("method", "listConfigLike");
                return "/admin/config/list";
            }
        }
    }

    @RequestMapping(
            params = {"method=detailConfig"},
            method = {RequestMethod.GET}
    )
    public String getConfigInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataId") String dataId, @RequestParam("group") String group, ModelMap modelMap) {
        dataId = dataId.trim();
        group = group.trim();
        ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
        modelMap.addAttribute("configInfo", configInfo);
        return "/admin/config/edit";
    }

    @RequestMapping(
            params = {"method=batchQuery"},
            method = {RequestMethod.POST}
    )
    public String batchQuery(HttpServletRequest request, HttpServletResponse response, @RequestParam("dataIds") String dataIds, @RequestParam("group") String group, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        if(StringUtils.isBlank(dataIds)) {
            throw new IllegalArgumentException("批量查询, dataIds不能为空");
        } else if(StringUtils.isBlank(group)) {
            throw new IllegalArgumentException("批量查询, group不能为空或者包含非法字符");
        } else {
            String[] dataIdArray = dataIds.split(Constants.WORD_SEPARATOR);
            group = group.trim();
            List<ConfigInfoEx> configInfoExList = new ArrayList();
            String[] arr$ = dataIdArray;
            int len$ = dataIdArray.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String dataId = arr$[i$];
                ConfigInfoEx configInfoEx = new ConfigInfoEx();
                configInfoEx.setDataId(dataId);
                configInfoEx.setGroup(group);
                configInfoExList.add(configInfoEx);

                try {
                    if(StringUtils.isBlank(dataId)) {
                        configInfoEx.setStatus(2);
                        configInfoEx.setMessage("dataId is blank");
                    } else {
                        ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
                        if(configInfo == null) {
                            configInfoEx.setStatus(2);
                            configInfoEx.setMessage("query data does not exist");
                        } else {
                            String content = configInfo.getContent();
                            configInfoEx.setContent(content);
                            configInfoEx.setStatus(1);
                            configInfoEx.setMessage("query success");
                        }
                    }
                } catch (Exception var16) {
                    log.error("批量查询, 在查询这个dataId时出错, dataId=" + dataId + ",group=" + group, var16);
                    configInfoEx.setStatus(-1);
                    configInfoEx.setMessage("query error: " + var16.getMessage());
                }
            }

            String json = null;

            try {
                json = JSONUtils.serializeObject(configInfoExList);
            } catch (Exception var15) {
                log.error("批量查询结果序列化出错, json=" + json, var15);
            }

            modelMap.addAttribute("json", json);
            return "/admin/config/batch_result";
        }
    }

    @RequestMapping(
            params = {"method=batchAddOrUpdate"},
            method = {RequestMethod.POST}
    )
    public String batchAddOrUpdate(HttpServletRequest request, HttpServletResponse response, @RequestParam("allDataIdAndContent") String allDataIdAndContent, @RequestParam("group") String group, ModelMap modelMap) {
        response.setCharacterEncoding("gbk");
        if(StringUtils.isBlank(allDataIdAndContent)) {
            throw new IllegalArgumentException("批量写, allDataIdAndContent不能为空");
        } else if(!StringUtils.isBlank(group) && !DiamondUtils.hasInvalidChar(group)) {
            String[] dataIdAndContentArray = allDataIdAndContent.split(Constants.LINE_SEPARATOR);
            group = group.trim();
            List<ConfigInfoEx> configInfoExList = new ArrayList();
            String[] arr$ = dataIdAndContentArray;
            int len$ = dataIdAndContentArray.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                String dataIdAndContent = arr$[i$];
                String dataId = dataIdAndContent.substring(0, dataIdAndContent.indexOf(Constants.WORD_SEPARATOR));
                String content = dataIdAndContent.substring(dataIdAndContent.indexOf(Constants.WORD_SEPARATOR) + 1);
                ConfigInfoEx configInfoEx = new ConfigInfoEx();
                configInfoEx.setDataId(dataId);
                configInfoEx.setGroup(group);
                configInfoEx.setContent(content);

                try {
                    if(StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId)) {
                        throw new IllegalArgumentException("批量写, dataId不能包含非法字符");
                    }

                    if(StringUtils.isBlank(content)) {
                        throw new IllegalArgumentException("批量写, 内容不能为空");
                    }

                    ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
                    String userName;
                    Timestamp time;
                    if(configInfo == null) {
                        userName = (String)request.getSession().getAttribute("user");
                        time = TimeUtils.getCurrentTime();

                        try {
                            this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.BATCHADDORUPDATE.toString(), dataId, group, content, content, time);
                        } catch (Exception var21) {
                            log.error("记录操作日志转json字符串异常");
                        }

                        this.configService.addConfigInfo(dataId, group, content);
                        configInfoEx.setStatus(3);
                        configInfoEx.setMessage("add success");
                    } else {
                        userName = (String)request.getSession().getAttribute("user");
                        time = TimeUtils.getCurrentTime();

                        try {
                            this.operatorRecordService.addOperatorRecord(userName, OperatorEnum.BATCHADDORUPDATE.toString(), dataId, group, content, content, time);
                        } catch (Exception var20) {
                            log.error("记录操作日志转json字符串异常");
                        }

                        this.configService.updateConfigInfo(dataId, group, content);
                        configInfoEx.setStatus(4);
                        configInfoEx.setMessage("update success");
                    }
                } catch (Exception var22) {
                    log.error("批量写这条数据时出错, dataId=" + dataId + ",group=" + group + ",content=" + content, var22);
                    configInfoEx.setStatus(-1);
                    configInfoEx.setMessage("batch write error: " + var22.getMessage());
                }

                configInfoExList.add(configInfoEx);
            }

            String json = null;

            try {
                json = JSONUtils.serializeObject(configInfoExList);
            } catch (Exception var19) {
                log.error("批量写, 结果序列化出错, json=" + json, var19);
            }

            modelMap.addAttribute("json", json);
            return "/admin/config/batch_result";
        } else {
            throw new IllegalArgumentException("批量写, group不能为空或者包含非法字符");
        }
    }

    @RequestMapping(
            params = {"method=listUser"},
            method = {RequestMethod.GET}
    )
    public String listUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        Map<String, String> userMap = this.adminService.getAllUsers();
        modelMap.addAttribute("userMap", userMap);
        return "/admin/user/list";
    }

    @RequestMapping(
            params = {"method=addUser"},
            method = {RequestMethod.POST}
    )
    public String addUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap modelMap) {
        if(!StringUtils.isBlank(userName) && !DiamondUtils.hasInvalidChar(userName.trim())) {
            if(!StringUtils.isBlank(password) && !DiamondUtils.hasInvalidChar(password.trim())) {
                if(this.adminService.addUser(userName, password)) {
                    modelMap.addAttribute("message", "添加成功!");
                } else {
                    modelMap.addAttribute("message", "添加失败!");
                }

                return this.listUser(request, response, modelMap);
            } else {
                modelMap.addAttribute("message", "无效的密码");
                return "/admin/user/new";
            }
        } else {
            modelMap.addAttribute("message", "无效的用户名");
            return this.listUser(request, response, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=deleteUser"},
            method = {RequestMethod.GET}
    )
    public String deleteUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, ModelMap modelMap) {
        if(!StringUtils.isBlank(userName) && !DiamondUtils.hasInvalidChar(userName.trim())) {
            if(this.adminService.removeUser(userName)) {
                modelMap.addAttribute("message", "删除成功!");
            } else {
                modelMap.addAttribute("message", "删除失败!");
            }

            return this.listUser(request, response, modelMap);
        } else {
            modelMap.addAttribute("message", "无效的用户名");
            return this.listUser(request, response, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=changePassword"},
            method = {RequestMethod.GET}
    )
    public String changePassword(HttpServletRequest request, HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap modelMap) {
        userName = userName.trim();
        password = password.trim();
        if(!StringUtils.isBlank(userName) && !DiamondUtils.hasInvalidChar(userName.trim())) {
            if(!StringUtils.isBlank(password) && !DiamondUtils.hasInvalidChar(password.trim())) {
                if(this.adminService.updatePassword(userName, password)) {
                    modelMap.addAttribute("message", "更改成功,下次登录请用新密码！");
                } else {
                    modelMap.addAttribute("message", "更改失败!");
                }

                return this.listUser(request, response, modelMap);
            } else {
                modelMap.addAttribute("message", "无效的新密码");
                return this.listUser(request, response, modelMap);
            }
        } else {
            modelMap.addAttribute("message", "无效的用户名");
            return this.listUser(request, response, modelMap);
        }
    }

    @RequestMapping(
            params = {"method=setRefuseRequestCount"},
            method = {RequestMethod.POST}
    )
    public String setRefuseRequestCount(@RequestParam("count") long count, ModelMap modelMap) {
        if(count <= 0L) {
            modelMap.addAttribute("message", "非法的计数");
            return "/admin/count";
        } else {
            GlobalCounter.getCounter().set(count);
            modelMap.addAttribute("message", "设置成功!");
            return this.getRefuseRequestCount(modelMap);
        }
    }

    @RequestMapping(
            params = {"method=getRefuseRequestCount"},
            method = {RequestMethod.GET}
    )
    public String getRefuseRequestCount(ModelMap modelMap) {
        modelMap.addAttribute("count", Long.valueOf(GlobalCounter.getCounter().get()));
        return "/admin/count";
    }

    @RequestMapping(
            params = {"method=reloadUser"},
            method = {RequestMethod.GET}
    )
    public String reloadUser(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        this.adminService.loadUsers();
        modelMap.addAttribute("message", "加载成功!");
        return this.listUser(request, response, modelMap);
    }

    public AdminService getAdminService() {
        return this.adminService;
    }

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    public ConfigService getConfigService() {
        return this.configService;
    }

    public void setConfigService(ConfigService configService) {
        this.configService = configService;
    }
}
